package com.zck.thumbup.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zck.thumbup.constant.RedisLuaScriptConstant;
import com.zck.thumbup.constant.ThumbConstant;
import com.zck.thumbup.entity.Blog;
import com.zck.thumbup.entity.Thumb;
import com.zck.thumbup.entity.User;
import com.zck.thumbup.exception.BusinessException;
import com.zck.thumbup.exception.ErrorCode;
import com.zck.thumbup.lock.RedisLock;
import com.zck.thumbup.mapper.ThumbMapper;
import com.zck.thumbup.model.dto.thumb.DoThumbRequest;
import com.zck.thumbup.model.enums.LuaStatusEnum;
import com.zck.thumbup.service.BlogService;
import com.zck.thumbup.service.ThumbService;
import com.zck.thumbup.service.UserService;
import com.zck.thumbup.util.RedisKeyUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 点赞服务实现类 - 使用@RedisLock注解方式
 */
@Service("thumbService")
@Slf4j
@RequiredArgsConstructor
public class ThumbServiceRedisImpl extends ServiceImpl<ThumbMapper, Thumb> implements ThumbService {

    private final UserService userService;
    private final RedisTemplate<String, Object> redisTemplate;


    @Override
    public Boolean doThumbByRedis(DoThumbRequest doThumbRequest, HttpServletRequest request) {
        if (doThumbRequest == null || doThumbRequest.getBlogId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数错误");
        }
        User loginUser = userService.getLoginUser(request);
        Long blogId = doThumbRequest.getBlogId();

        //计算时间片
        String timeSlice = getTimeSlice();
        //Redis key
        String tempThumbKey = RedisKeyUtil.getTempThumbKey(timeSlice);
        String userThumbKey = RedisKeyUtil.getUserThumbKey(loginUser.getId());

        //execute()传入的参数不需要传为string的
        String now = DateUtil.now();
        //执行Lua脚本
        Long result = redisTemplate.execute(
                RedisLuaScriptConstant.UNTHUMB_SCRIPT,
                Arrays.asList(tempThumbKey, userThumbKey),
                loginUser.getId(),
                blogId,
                now
        );

        if (result== LuaStatusEnum.FAIL.getValue()) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"用户未点赞");
        }

        return LuaStatusEnum.SUCCESS.getValue()==result;
    }

    @Override
    public Boolean undoThumbByRedis(DoThumbRequest doThumbRequest, HttpServletRequest request) {
        return null;
    }

    @Override
    public Boolean hasThumb(Long blogId, Long userId) {
        return redisTemplate.opsForHash().hasKey(RedisKeyUtil.getUserThumbKey(userId),blogId.toString());
    }

    private String getTimeSlice(){
        DateTime nowDate = DateUtil.date();
        //获取到当前时间前最近的整数秒,比如当前 11:20:23,获取到11:20:20
        return DateUtil.format(nowDate,"HH:mm:")+(DateUtil.second(nowDate)/10)*10;
    }
}